#include "state_game.h"

void CStateGame::Init()
{

  m_Tag = "StateGame";
  
  m_iStateMessage = 1;
  
  m_pPlayer = NULL;

  
}

void CStateGame::PreRun()
{
	
	m_pGameInterface->RegisterLuaEngineHooks();
	m_pGameInterface->OpenScript( LUA_START_FILE );
	
	m_pPlayer = m_pGameInterface->GetPlayer();
	m_pPlayer->SetPos( 10, 10 );
	m_pPlayer->FitCollisionBoxToSprite( 0, .85f );
	
	m_pGameInterface->LoadMap( "maps/test.map" );
	
}

void CStateGame::Input()
{
	
	SDL_Event ev;
	
	SDL_PollEvent( &ev );
	
	Uint8 * keys = SDL_GetKeyState( NULL );
		
	if( keys[SDLK_DOWN] )
	{
		
		m_pPlayer->SetPhysicsVel( 0.0f, 150.0f );
		m_pPlayer->SetCurrentSpriteBind( SB_DOWNRUN );
		
	} else if( keys[SDLK_LEFT] )
	{
		
		m_pPlayer->SetPhysicsVel( -150.0f, 0.0f );
		m_pPlayer->SetCurrentSpriteBind( SB_LEFTRUN );
		
		if( m_pPlayer->IsFlipped() )
			m_pPlayer->Flip();
		
	} else if( keys[SDLK_RIGHT] )
	{
		
		m_pPlayer->SetPhysicsVel( 150.0f, 0.0f );
		m_pPlayer->SetCurrentSpriteBind( SB_LEFTRUN );
		
		if( !m_pPlayer->IsFlipped() )
			m_pPlayer->Flip();
		
	} else if( keys[SDLK_UP] )
	{
		
		m_pPlayer->SetPhysicsVel( 0.0f, -150.0f );
		m_pPlayer->SetCurrentSpriteBind( SB_UP );
		
	} else
	{
		
		m_pPlayer->SetPhysicsVel( 0.0f, 0.0f );
		
		switch( m_pPlayer->GetCurrentSpriteBind() )
		{
			
			case SB_DOWNRUN:
				m_pPlayer->SetCurrentSpriteBind( SB_DOWN );
				break;
			case SB_LEFTRUN:
				m_pPlayer->SetCurrentSpriteBind( SB_LEFT );
				break;
			case SB_UP:
				break;
			default:
				break;
			
		}
		
	}
	
	
	if( ev.key.keysym.sym == SDLK_ESCAPE )
	{
	
		m_iStateMessage = 0;
		
	}
	
	if( ev.type == SDL_QUIT )
	{
	
		m_iStateMessage = 0;
		
	}

}

void CStateGame::Think()
{

	m_pGameInterface->GetEntityFactory()->EntitiesThink();
	
	m_pGameInterface->HandleMapCollision();
	
}

void CStateGame::Draw()
{

	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glLoadIdentity();
	
	m_pGameInterface->GetMap()->DrawOutline();
	m_pGameInterface->GetMap()->DrawDisplayList();
	
	m_pGameInterface->GetEntityFactory()->DrawEntitiesToFrameBuffers();
	m_pGameInterface->GetFrameScene()->Draw();

	m_pGameInterface->CallEngineHook( "PostDraw" );

	SDL_GL_SwapBuffers();
	
}